package siwi.map.android;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.alibaba.fastjson.JSON;
import com.wmw.Animation.ViewAction;
import com.wmw.Utility.Common;
import com.wmw.Utility.SRConstant;
import com.wmw.music.AllMusicMessage;
import com.wmw.music.Constant;
import com.wmw.music.MediaPlayerService;
import com.wmw.music.MusicData;
import com.wmw.music.Util;

public class SettingRing extends SherlockActivity {
	// 无手机铃声时,无限崩
	// SD卡拔出后,能否正常播放.
	// 开机启动
	//

	private final static int _ImmediateRing = 0;
	private final static int _DelayRing = 1;

	TextView _immediateRingName, _delayRingName;
	ImageView _playImmediateRing, _playDelayRing;
	int _curPlayingIdx;
	boolean _bPlayingImmediateRing = false, _bPlayingDelayRing = false;
	String[] musicNames;
	MediaPlayer _player = new MediaPlayer();

	Uri shortRing, longRing;
	String shortRingName, longRingName;
	String DATA = MediaStore.Audio.Media.DATA;
	String TITLE = MediaStore.Audio.Media.TITLE;
	String DURATION = MediaStore.Audio.Media.DURATION;
	String ARTIST_ID = MediaStore.Audio.Media.ARTIST_ID;
	String ALBUM_ID = MediaStore.Audio.Media.ALBUM_ID;
	String YEAR = MediaStore.Audio.Media.YEAR;

	String ARTIST = MediaStore.Audio.Media.ARTIST;
	String ALBUM = MediaStore.Audio.Media.ALBUM;

	Uri uri_meta = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
	Intent _playMusicIntent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initActionBar();

		setContentView(R.layout.setting_ring);

		initViews();
		initData();
	}

	private void initActionBar() {
		// Custom action bar.
		ActionBar actionBar = getSupportActionBar();
		ActionBar.LayoutParams params = new ActionBar.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
				Gravity.CENTER);
		View view = LayoutInflater.from(this).inflate(
				R.layout.action_bar_back_save, null);
		actionBar.setCustomView(view, params);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);

		TextView tv = (TextView) view.findViewById(R.id.ABBS_Title);
		tv.setText("铃声设置");

		findViewById(R.id.ABBS_Back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewAction.startSpringMenuAnimations(v);
				// Go back.
				Log.d(Common.GetLineInfo(), "Go back without saving");
				goBack();
				return;
			}
		});

		findViewById(R.id.ABBS_Save).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewAction.startSpringMenuAnimations(v);
				Log.d(Common.GetLineInfo(), "Go back and saving");
				saveRing();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
				SettingRing.this.finish();
				return;
			}

		});
	}

	@Override
	public void onStop() {
		super.onStop();
		stopPlay();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;

		switch (id) {
		case _ImmediateRing:
			dialog = new AlertDialog.Builder(SettingRing.this)
					.setTitle("")
					.setItems(musicNames,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Log.d(Common.GetLineInfo(),
											"You selected: " + which + " , "
													+ musicNames[which]);
									_immediateRingName
											.setText(musicNames[which]);

									Constant.currentArr = Constant.ALL;
									Constant.currentIndex = which;
									_playImmediateRing
											.setImageResource(R.drawable.music_pause);

									Constant.title = MusicData.allMusicList
											.get(which).getTitle();
									Constant.artist = MusicData.allMusicList
											.get(which).getArtist();
									Constant.duration = MusicData.allMusicList
											.get(which).getDuration();
									Constant.total = Util
											.toTime(MusicData.allMusicList.get(
													which).getDuration());
									Constant._data = MusicData.allMusicList
											.get(which).get_data();

									_playMusicIntent.putExtra(Constant.FLAG,
											Constant.ALL);
									_playMusicIntent.putExtra(
											Constant.POSITION, which);
									startService(_playMusicIntent);
								}
							}).create();
			break;

		case _DelayRing:
			dialog = new AlertDialog.Builder(SettingRing.this)
					.setTitle("")
					.setItems(R.array.select_dialog_items,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									String[] items = getResources()
											.getStringArray(
													R.array.select_dialog_items);
									Log.d(Common.GetLineInfo(),
											"You selected: " + which + " , "
													+ items[which]);
									_immediateRingName.setText(items[which]);
								}
							}).create();
			break;
		default:
			Log.e(Common.GetLineInfo(), "Unexpected error");
			break;
		}

		return dialog;
	}

	// 检测是否存在指定的文件夹
	// 如果不存在则创建
	private boolean bFolder(String strFolder) {
		boolean btmp = false;
		File f = new File(strFolder);
		if (!f.exists()) {
			if (f.mkdirs()) {
				btmp = true;
			} else {
				btmp = false;
			}
		} else {
			btmp = true;
		}
		return btmp;
	}

	private void saveRing() {
		ExApplication app = (ExApplication)getApplication();
		app._ImmdediateRing = shortRing;
		app._DelayRing = longRing;
		saveDataToReferences(SRConstant._SettingRing, SRConstant._SR_ShortRing, shortRing);
		saveDataToReferences(SRConstant._SettingRing, SRConstant._SR_LongRing, longRing);
	}

	private void initViews() {
		findViewById(R.id.SR_ImmediateRing).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {

						// Uri pickedUri = RingtoneManager
						// .getActualDefaultRingtoneUri(SettingRing.this,
						// RingtoneManager.TYPE_RINGTONE);
						// playUri(pickedUri, SettingRing.this);
						stopPlay();
						if (bFolder("/sdcard/music/ringtones")) {
							// 打开系统铃声设置
							Intent intent = new Intent(
									RingtoneManager.ACTION_RINGTONE_PICKER);
							// 类型为来电RINGTONE
							intent.putExtra(
									RingtoneManager.EXTRA_RINGTONE_TYPE,
									RingtoneManager.TYPE_RINGTONE);
							// 设置显示的title
							intent.putExtra(
									RingtoneManager.EXTRA_RINGTONE_TITLE,
									"设置订单即时铃声");
							// 当设置完成之后返回到当前的Activity
							startActivityForResult(intent, _ImmediateRing);
						}
					}

				});
		findViewById(R.id.SR_DelayRing).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						stopPlay();
						// TODO
						// SD卡拔出时
						if (bFolder("/sdcard/music/ringtones")) {
							// 打开系统铃声设置
							Intent intent = new Intent(
									RingtoneManager.ACTION_RINGTONE_PICKER);
							// 类型为来电RINGTONE
							intent.putExtra(
									RingtoneManager.EXTRA_RINGTONE_TYPE,
									RingtoneManager.TYPE_RINGTONE);
							// 设置显示的title
							intent.putExtra(
									RingtoneManager.EXTRA_RINGTONE_TITLE,
									"1分钟无响应订单铃声");
							// 当设置完成之后返回到当前的Activity
							startActivityForResult(intent, _DelayRing);
						}
					}

				});
		_immediateRingName = (TextView) findViewById(R.id.SR_ImmediateRingName);
		_playImmediateRing = (ImageView) findViewById(R.id.SR_PlayImmediateRing);
		_playImmediateRing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (_bPlayingImmediateRing || _bPlayingDelayRing) {
					boolean bPlayingOther = _bPlayingDelayRing;
					stopPlay();
					if (bPlayingOther) {
						playUri(shortRing, SettingRing.this, _playImmediateRing);
						_bPlayingImmediateRing = true;
					}
				} else {
					playUri(shortRing, SettingRing.this, _playImmediateRing);
					_bPlayingImmediateRing = true;
				}
			}
		});

		_delayRingName = (TextView) findViewById(R.id.SR_DelayRingName);
		_playDelayRing = (ImageView) findViewById(R.id.SR_PlayDelayRing);
		_playDelayRing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (_bPlayingImmediateRing || _bPlayingDelayRing) {
					boolean bPlayingOther = _bPlayingImmediateRing;
					stopPlay();
					if (bPlayingOther) {
						playUri(longRing, SettingRing.this, _playDelayRing);
						_bPlayingDelayRing = true;
					}
				} else {
					playUri(longRing, SettingRing.this, _playDelayRing);
					_bPlayingDelayRing = true;
				}
			}
		});

	}

	private void initData() {
		_curPlayingIdx = 0;
		_playMusicIntent = new Intent(SettingRing.this,
				MediaPlayerService.class);

		Cursor cs_meta = getContentResolver().query(uri_meta,
				new String[] { DATA, TITLE, DURATION, ARTIST, ALBUM, YEAR },
				null, null, null);
		if (cs_meta != null && cs_meta.getCount() > 0) {
			while (cs_meta.moveToNext()) {
				AllMusicMessage allMusicMessage = new AllMusicMessage();
				allMusicMessage.set_data(cs_meta.getString(0));
				allMusicMessage.setTitle(cs_meta.getString(1));
				allMusicMessage.setDuration(cs_meta.getInt(2));
				allMusicMessage.setArtist(cs_meta.getString(3));
				allMusicMessage.setAlbum(cs_meta.getString(4));
				String year = String.valueOf(cs_meta.getInt(5));
				if (year.equals("0")) {
					year = "未知年份";
				}
				allMusicMessage.setYear(year);

				MusicData.allMusicList.add(allMusicMessage);
			}
		}

		int len = MusicData.allMusicList.size();
		musicNames = new String[len];
		for (int i = 0; i < len; ++i)
			musicNames[i] = MusicData.allMusicList.get(i).getTitle();

		ExApplication app = (ExApplication)getApplication();
		shortRing = app._ImmdediateRing;
		longRing = app._DelayRing;

		_immediateRingName.setText(RingtoneManager.getRingtone(
				SettingRing.this, shortRing).getTitle(SettingRing.this));

		_delayRingName.setText(RingtoneManager.getRingtone(SettingRing.this,
				longRing).getTitle(SettingRing.this));
	}

	public <T> boolean isDataInReferences(String shareName, String key) {
		SharedPreferences preferences = getSharedPreferences(shareName,
				MODE_PRIVATE);
		String str = preferences.getString(key, "");
		Log.d(Common.GetLineInfo(), str + ", empty -" + str.isEmpty());
		return !str.isEmpty() ? true : false;
	}

	public Uri readDataFromReferences(String shareName, String key, Uri d) {
		SharedPreferences preferences = getSharedPreferences(shareName,
				MODE_PRIVATE);
		String value = preferences.getString(key, "");
		return Uri.parse(value);
	}

	public boolean saveDataToReferences(String referenceName, String key,
			Uri data) {
		SharedPreferences preferences = getSharedPreferences(referenceName,
				MODE_PRIVATE);
		boolean success = false;
		Editor editor = preferences.edit();
		editor.putString(key, data.toString());
		editor.commit();

		success = true;
		Log.d(Common.GetLineInfo(), "Save data to references success -" + data);

		return success;
	}

	private void play() {
		switch (Constant.currentState) {
		case Constant.PLAY:
			Constant.currentState = Constant.PAUSE;
			break;
		case Constant.PAUSE:
			Constant.currentState = Constant.PLAY;
			break;
		}
		checkPlayModel();
		startService();
	}

	private void startService() {
		_playMusicIntent.putExtra(Constant.FLAG, Constant.PLOPA);
		startService(_playMusicIntent);
	}

	private void checkPlayModel() {
		switch (Constant.currentState) {
		case Constant.PLAY:
			_playImmediateRing.setImageResource(R.drawable.music_pause);
			break;
		case Constant.PAUSE:
			_playImmediateRing.setImageResource(R.drawable.music_play);
			break;
		}
	}

	/* 当设置铃声之后的回调函数 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case _ImmediateRing:
			// 得到我们选择的铃声
			shortRing = data
					.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
			_immediateRingName.setText(RingtoneManager.getRingtone(
					SettingRing.this, shortRing).getTitle(SettingRing.this));
			playUri(shortRing, SettingRing.this, _playImmediateRing);
			_bPlayingImmediateRing = true;
			break;

		case _DelayRing:
			longRing = data
					.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
			_delayRingName.setText(RingtoneManager.getRingtone(
					SettingRing.this, longRing).getTitle(SettingRing.this));
			playUri(longRing, SettingRing.this, _playDelayRing);
			_bPlayingDelayRing = true;
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void stopPlay() {
		_player.stop();
		_player.reset();
		_playImmediateRing.setImageResource(R.drawable.music_play);
		_playDelayRing.setImageResource(R.drawable.music_play);
		_bPlayingImmediateRing = false;
		_bPlayingDelayRing = false;
	}




	private void playUri(Uri pickedUri, Context context, ImageView iv) {
		try {
			_player.setDataSource(context, pickedUri);
		} catch (Exception e) {
			e.printStackTrace();
		}
		final AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
			_player.setAudioStreamType(AudioManager.STREAM_ALARM);
			_player.setLooping(true);

			try {
				_player.prepare();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			_player.start();

			iv.setImageResource(R.drawable.music_pause);
		}
	}

	private void goBack() {
		Intent intent = new Intent();
		intent.setClass(SettingRing.this, Home.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(intent);
		overridePendingTransition(R.anim.left_in, R.anim.right_out);
		SettingRing.this.finish();
	}
}
